from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from ..database import get_db
from ..models.models import Student
from ..schemas import StudentResponse, MatchingResponse
from ..services.roommate_matching import RoommateMatchingService
from .auth import get_current_user

router = APIRouter(
    prefix="/matching",
    tags=["室友匹配"]
)

@router.get("/candidates", response_model=List[MatchingResponse])
async def get_matching_candidates(
    limit: int = 10,
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取匹配的室友候选人"""
    # 获取所有可能的候选人（同性别、未分配宿舍的学生）
    candidates = (
        db.query(Student)
        .filter(
            Student.gender == current_user.gender,
            Student.id != current_user.id,
            Student.room_id.is_(None)
        )
        .all()
    )
    
    # 使用匹配服务计算兼容性分数
    matching_service = RoommateMatchingService(db)
    matches = matching_service.find_best_roommates(
        student=current_user,
        candidates=candidates,
        required_count=limit
    )
    
    # 转换为响应格式
    return [
        MatchingResponse(
            student=candidate,
            compatibility_score=score
        )
        for candidate, score in matches
    ]

@router.get("/mutual-preferences", response_model=List[MatchingResponse])
async def get_mutual_preferences(
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取互相选择的室友"""
    matching_service = RoommateMatchingService(db)
    mutual_matches = matching_service.get_mutual_preferences(db, current_user.id)
    
    return [
        MatchingResponse(
            student=student,
            compatibility_score=score
        )
        for student, score in mutual_matches
    ]

@router.get("/recommended-groups", response_model=List[List[StudentResponse]])
async def get_recommended_groups(
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取推荐的室友组合"""
    # 获取同性别、未分配宿舍的学生
    available_students = (
        db.query(Student)
        .filter(
            Student.gender == current_user.gender,
            Student.room_id.is_(None)
        )
        .all()
    )
    
    if current_user not in available_students:
        available_students.append(current_user)
    
    # 使用匹配服务生成最优组合
    matching_service = RoommateMatchingService(db)
    groups = matching_service.generate_roommate_groups(
        students=available_students,
        room_size=4  # 每个宿舍最多4人
    )
    
    # 只返回包含当前用户的组合
    user_groups = [
        group for group in groups 
        if current_user in group
    ]
    
    return user_groups

@router.get("/compatibility/{student_id}", response_model=float)
async def get_compatibility_score(
    student_id: int,
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取与特定学生的兼容性分数"""
    target_student = db.query(Student).filter(Student.id == student_id).first()
    if not target_student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="目标学生不存在"
        )
        
    matching_service = RoommateMatchingService(db)
    score = matching_service.calculate_compatibility_score(
        current_user,
        target_student
    )
    
    return score 